/* eslint-disable */
import * as d3 from '../../../static/js/d3.js'
function JusTree(params) {
  height = this.height = params.height
    ? params.height
    : document.querySelector(params.id).clientHeight
  width = this.width = params.width
    ? params.width
    : document.querySelector(params.id).clientWidth
  this.wrapper = params.id ? params.id : 'body'
  this.data = params.data ? params.data : {}
  this.colors = params.colors || [
    '#0f0',
    '#00f',
    '#469EE9',
    '#53C76B',
    '#FF3C00',
    '#41CB5D'
  ]
  this.svgDom = null
  this.flag = true
  this.root = null
  this.g = null
  this.duration = 750
  this.tree = null
}

JusTree.prototype = {
  init: function() {
    this.createSvg()
    this.createChart()
  },
  // 创建svg
  createSvg: function() {
    this.svgDom = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
    this.svg = d3
      .select(this.svgDom)
      .attr('width', this.width)
      .attr('height', this.height)
  },
  // 创建树状图前期准备
  createChart: function() {
    var _this = this
    // 创建图表的时候清空容器元素
    document.querySelector(this.wrapper).innerHTML = ''
    d3.select(this.svgDom).remove()

    // 设置图表缩放事件
    this.zoom = d3
      .zoom()
      .scaleExtent([0.1, 2])
      .on('zoom', redraw)

    function redraw() {
      _this.g.attr('transform', d3.event.transform)
    }

    this.g = this.svg.append('g')
    this.svg.call(this.zoom)

    // 定义树布局
    this.tree = d3
      .tree()
      .size([2 * Math.PI, this.width / 2 - 150])
      .separation(function(a, b) {
        return (a.parent === b.parent ? 1 : 2) / a.depth
      })
    // 获取树布局的节点连线信息
    this.root = this.tree(d3.hierarchy(this.data))
    this.root.x0 = this.height / 2
    this.root.y0 = 0
    if (this.root.children[0].children || this.root.children[1].children) {
      this.zoom.scaleTo(this.svg, 1.3)
    }

    // 每个节点分支赋予不同的颜色
    if (this.root.children) {
      this.root.children.forEach(function(item, index) {
        item.color = _this.colors[index]
        item.rSize = 8
        _this._setColor(item, item.color, item.rSize)
      })
    }
    if (this.root.children.length > 0) {
      this.root.children.forEach(function(item) {
        if (item.children) {
          item.children.forEach(collapse)
        }
      })
    }

    this.update(this.root)

    document.querySelector(this.wrapper).appendChild(this.svgDom)
  },
  // 树状图更新方法
  update: function(source) {
    var treeData = this.tree(this.root)
    var nodes = treeData.descendants()
    var links = treeData.descendants().slice(1)
    nodes.forEach(function(d) {
      d.y = d.depth * 180
    })
    this._setNode(nodes)
    this._setLink(links)
  },
  // 设置节点包括圆、文本以及符号
  _setNode: function(nodes) {
    var i = 0
    var _this = this
    var node = this.g.selectAll('g.node').data(nodes, function(d) {
      return d.id || (d.id = ++i)
    })
    var nodeEnter = node
      .enter()
      .append('g')
      .attr('class', 'node')
      .attr('transform', function(d) {
        return 'translate(' + radialPoint(d.x, d.y) + ')'
      })
      .on('click', function(d) {
        console.log(d)
        if (d.children) {
          d._children = d.children
          d.children = null
        } else {
          d.children = d._children
          d._children = null
        }
        _this.update(d)
      })
    this._initCircle(nodeEnter)
    this._initText(nodeEnter)
    var nodeUpdate = nodeEnter.merge(node)
    nodeUpdate
      .transition()
      .duration(this.duration)
      .attr('transform', function(d) {
        return 'translate(' + radialPoint(d.x, d.y) + ')'
      })
    nodeUpdate
      .select('circle.node')
      .attr('r', 10)
      .attr('cursor', 'pointer')
    nodeUpdate.select('text.flag').text(function(d) {
      if (d._children && d.depth > 0) {
        return '+'
      } else if (d.children && d.depth > 0) {
        return '-'
      }
    })
    var nodeExit = node
      .exit()
      .transition()
      .duration(this.duration)
      .attr('transform', function(d) {
        return 'translate(' + radialPoint(d.x, d.y) + ')'
      })
      .remove()
    nodeExit
      .select('circle')
      .attr('r', 1e-6)
      .remove()
    nodeExit
      .select('text')
      .style('fill-opacity', 1e-6)
      .remove()
    nodes.forEach(function(d) {
      d.x0 = d.x
      d.y0 = d.y
    })
  },
  // 设置连线
  _setLink: function(links) {
    var link = this.g.selectAll('path.link').data(links, function(d) {
      return d.id
    })
    link.exit().remove()
    var linkEnter = link
      .enter()
      .insert('path', 'g')
      .attr('class', 'link')
      .style('stroke', function(d) {
        return d.color
      })
      .style('stroke-width', '1.5px')
      .style('stroke-opacity', 0.4)
      .style('stroke-dasharray', 10)
      .style('fill', 'none')

    var linkUpdate = linkEnter.merge(link)
    linkUpdate
      .transition()
      .duration(this.duration)
      .style('stroke', function(d) {
        return d.color
      })
      .attr('d', function(d) {
        return (
          'M' +
          radialPoint(d.x, d.y) +
          'C' +
          radialPoint(d.x, (d.y + d.parent.y) / 2) +
          ' ' +
          radialPoint(d.parent.x, (d.y + d.parent.y) / 2) +
          ' ' +
          radialPoint(d.parent.x, d.parent.y)
        )
      })
  },
  // 数据准备阶段需要的赋予颜色函数
  _setColor: function(node, color, size) {
    if (node.children) {
      var rSize = size - 2
      node.children.forEach(child => {
        child.color = color
        child.rSize = rSize
        this._setColor(child, color, child.rSize)
      })
    }
  },
  // 初始化节点中的圆
  _initCircle: function(node) {
    node
      .append('circle')
      .attr('r', function(d, i) {
        return d.rSize ? d.rSize : 16
      })
      .attr('class', 'node')
      .style('fill', function(d, i) {
        return d.color ? d.color : '#f00'
      })

    node
      .append('text')
      .attr('dy', function(d, i) {
        return d.rSize ? d.rSize - 2 : 12 - 4
      })
      .attr('class', 'flag')
      .attr('text-anchor', 'middle')
      .style('fill', '#fff')
      .style('cursor', 'pointer')
      .style('font-size', function(d) {
        return d.rSize ? d.rSize * 2.5 : 12 * 2.5
      })
      .text(function(dd) {
        return (function(d) {
          if (d._children && d.depth > 0) {
            return '+'
          } else if (d.children && d.depth > 0) {
            return '-'
          }
        })(dd)
      })
    node
      .append('image')
      .attr('style', function(data) {
        if (data.data.isRisk) {
          return 'transform:translate(2px,-20px);opacity:1'
        } else {
          return 'transform:translate(2px,-20px);opacity:0'
        }
      })
      .attr('xlink:href',require('../../../static/images/warning.png'))
      .attr('width', '16px')
      .attr('height', '16px')
  },
  // 初始化节点中文本
  _initText: function(node) {
    node
      .append('a')
      .attr('xlink:href', 'javascript:void(0)')
      .on('click', function(event) {
        if (event.data.exist) {
          let detailHref =
            'http://' +
            location.host +
            '#/entdetail/baseinfo?entid=' +
            event.data.exist +
            '&entname=' +
            event.data.name
          window.open(detailHref)
          // location.href = window.api_host + '/entdetail/baseinfo?entid=' + event.data.exist + '&entname=' + event.data.name
        }
      })
      .attr('target', '_blank')
      .append('text')
      .attr('dy', '0.31em')
      .style('font', '10px sans-serif')
      .attr('x', function(d) {
        return d.x < Math.PI === !d.children ? 20 : -20
      })
      .attr('text-anchor', function(d) {
        return d.x < Math.PI === !d.children ? 'start' : 'end'
      })
      .attr('cursor', function(d) {
        return d.data.isRisk ? 'pointer' : 'text'
      })
      .attr('transform', function(d) {
        if (d.depth > 0) {
          return (
            'rotate(' +
            ((d.x < Math.PI ? d.x - Math.PI / 2 : d.x + Math.PI / 2) * 180) /
              Math.PI +
            ')'
          )
        } else {
          return 'rotate(0)'
        }
      })
      .text(function(d) {
        return d.data.name
      })
  }
}
export default JusTree

// 提供给计算坐标方法的公有属性
var width = 0
var height = 0
var that = this
// 改变数据使只显示到第二层
function collapse(d) {
  // console.log(d)
  // if (d.children) {
  //   d._children = d.children
  //   d._children.forEach(collapse)
  //   d.children = null
  // }
}
// 计算节点和线的坐标
function radialPoint(x, y) {
  return [
    (y = +y) * Math.cos((x -= Math.PI / 2)) + width / 2,
    y * Math.sin(x) + height / 2
  ]
}



// WEBPACK FOOTER //
// ./src/assets/js/jus_tree.js